package com.tianxinweb.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tianxinweb.entity.Role;
import com.tianxinweb.enums.ResultEnum;
import com.tianxinweb.exception.MyException;
import com.tianxinweb.mapper.RoleMapper;
import com.tianxinweb.service.RoleService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cboy
 * @since 2018-07-19
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Override
    public Page getRoleList(Integer pn, Integer size, String key) {
        if("".equals(key)) return selectPage(new Page<>(pn,size));
        return selectPage(new Page<>(pn,size), new EntityWrapper<Role>()
                .like("role_name",key));
    }

    @Override
    public Role selectByRoleName(String roleName) {
        return selectOne(new EntityWrapper<Role>().eq("role_name",roleName));
    }

    @Override
    public void addRole(Role role) {
        Set<Integer> set = checkPriv(role.getPriviIds());
        Role dbRole = new Role();
        dbRole.setPriviIds(JSON.toJSONString(set));
        dbRole.setRoleDesc(role.getRoleDesc()==null?"":role.getRoleDesc());
        dbRole.setRoleName(role.getRoleName());
        insert(dbRole);
    }

    private Set<Integer> checkPriv(String idsStr){
        Set<Integer> set = new HashSet<>();
        try{
            String[] ids = idsStr.split(",");
            for(String id :ids){
                set.add(Integer.parseInt(id));
            }
        }catch (Exception e){
            throw new MyException(ResultEnum.PARAMETER_FORMAT_ERROR);
        }
        if(set.isEmpty()){
            throw new MyException(ResultEnum.ROLE_PRIVILEGE_EMPTY_ERROR);//角色权限id不能为空
        }

        int count = selectCount(new EntityWrapper<Role>().in("role_id",set));
        if(count==0) throw new MyException(ResultEnum.ROLE_PRIVILEGE_EMPTY_ERROR);//角色权限id不能为空

        return set;
    }

    @Override
    public void updateRole(Role role) {
        Set<Integer> set = checkPriv(role.getPriviIds());
        Role dbRole = new Role();
        dbRole.setRoleId(role.getRoleId());
        dbRole.setPriviIds(JSON.toJSONString(set));
        dbRole.setRoleDesc(role.getRoleDesc()==null?"":role.getRoleDesc());
        dbRole.setRoleName(role.getRoleName());
        updateById(dbRole);
    }
}
